package com.dlc.shop.delivery.api.listener;

import cn.hutool.core.collection.CollUtil;
import com.dlc.shop.bean.app.dto.ShopCartItemDto;
import com.dlc.shop.bean.app.vo.ProductVO;
import com.dlc.shop.bean.dto.TransfeeDto;
import com.dlc.shop.bean.dto.TransportDto;
import com.dlc.shop.bean.enums.ProdType;
import com.dlc.shop.bean.event.CheckAddrEvent;
import com.dlc.shop.bean.model.Area;
import com.dlc.shop.bean.model.UserAddr;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.delivery.common.model.Transport;
import com.dlc.shop.delivery.common.service.TransportService;
import com.dlc.shop.service.UserAddrService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lanhai
 */
@Component("checkAddrListener")
@AllArgsConstructor
public class CheckAddrListener {
    private final TransportService transportService;

    private final UserAddrService userAddrService;

    /**
     * 判断用户默认地址是否超出配送区域
     *
     * @param event
     */
    @EventListener(CheckAddrEvent.class)
    public void checkAddrListenerEvent(CheckAddrEvent event) {
        String userId = event.getUserId();
        if (CollUtil.isNotEmpty(event.getShopCartItemList())) {
            Map<Long, TransportDto> transportMap = new HashMap<>(Constant.INITIAL_CAPACITY);
            UserAddr userAddr = event.getUserAddr();
            List<ShopCartItemDto> shopCartItemList = event.getShopCartItemList();
            for (ShopCartItemDto shopCartItemDto : shopCartItemList) {
                if(Objects.equals(shopCartItemDto.getProdType(), ProdType.PROD_TYPE_ACTIVE.value()) || Objects.equals(userId, null)){
                    shopCartItemDto.setIsDelivery(true);
                    continue;
                }
                if(Objects.equals(shopCartItemDto.getMold(), 1) ){
                    shopCartItemDto.setIsDelivery(true);
                    continue;
                }
                TransportDto transport = transportMap.get(shopCartItemDto.getShopId());
                shopCartItemDto.setIsDelivery(check(shopCartItemDto.getDeliveryTemplateId(), userId, userAddr, transport));
                if (Objects.nonNull(transport) && !transportMap.containsKey(shopCartItemDto.getDeliveryTemplateId())) {
                    transportMap.put(shopCartItemDto.getDeliveryTemplateId(), transport);
                }
            }
            event.setTransportMap(transportMap);
        }else{
            ProductVO productVO = event.getProductVO();
            if(Objects.isNull(productVO)){
                return;
            }
            UserAddr userAddr = userAddrService.getUserAddrByUserId(event.getAddrId(), userId);
            productVO.setIsDelivery(check(productVO.getDeliveryTemplateId(), userId, userAddr, null));
        }
    }

    private Boolean check(Long deliveryTemplateId, String userId, UserAddr userAddr, TransportDto transprot) {
        if (Objects.isNull(userId) || Objects.isNull(userAddr) || Objects.isNull(deliveryTemplateId) ||
                deliveryTemplateId == 0 || deliveryTemplateId == -1) {
            return true;
        }
        if (Objects.isNull(transprot)) {
            Transport transprotDb = transportService.getTransportAndAllItems(deliveryTemplateId);
            transprot = BeanUtil.map(transprotDb, TransportDto.class);
        }
        if (transprot.getIsFreeFee() == 1) {
            return true;
        }
        List<Area> areaList = new ArrayList<>();
        List<TransfeeDto> transFees = transprot.getTransfees();
        if (!transFees.isEmpty()) {
            for (TransfeeDto transFee : transFees) {
                areaList.addAll(transFee.getCityList());
            }
        }
        Map<Long, List<Area>> areaMap = areaList.stream().collect(Collectors.groupingBy(Area::getAreaId));
        if (areaMap.containsKey(userAddr.getAreaId())) {
            return true;
        } else {
            return false;
        }
    }
}
